package com.example.security;


import com.example.security.deserializer.GrantedAuthorityDeserializer;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Data
@JsonIgnoreProperties(ignoreUnknown = true) // 标注 UserDetail 类以忽略未知属性
@NoArgsConstructor
public class UserDetail implements UserDetails {
    private static final long serialVersionUID = 1L;

    public Long id;
    public String username;
    public String password;
    public Integer status;
    public Long deptId;
    public Long tenantId;
    public Long storeId;
    public Integer isHeadStore;
    public Integer isSuperTenant;
    public Long clientPrimaryId;
    public Integer isBusinessUser; // 1:是业务用户， 0：后台管理员用户
    public Collection<? extends GrantedAuthority> authorities;

    public UserDetail(Long id, String username, String password, Integer status, Long deptId, Long tenantId, Long storeId, Integer isHeadStore, Integer isSuperTenant, Integer isBusinessUser, Set<String> permissions) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.status = status;
        this.deptId = deptId;
        this.storeId = storeId;
        this.tenantId = tenantId;
        this.isHeadStore = isHeadStore;
        this.isSuperTenant  = isSuperTenant;
        this.isBusinessUser = isBusinessUser;
        this.authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }


    @Override
    @JsonDeserialize(using = GrantedAuthorityDeserializer.class)
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.status == 1;
    }
} 